package com.hg.library.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.hg.library.http.HttpAgent;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ASUS-PC on 2016/8/5.
 */
public class NetworkUtils {
    public static final class NetSpeed {
        private Context mContext;
        private CallBack mCallBack;
        private float rx;
        private Timer timer;
        private float tempR;

        private String TEST_URL = "http://resource.hispot.cn/hios/rk322x_box/v1.2.0.1/update.zip";

        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                float r = (float) msg.obj;
                tempR = r;
                if (mCallBack != null) {
                    mCallBack.onNetworkSpeed(tempR, tempR / 1024, tempR / 1024 / 1024, msg.what);
                }
            }
        };

        public NetSpeed(Context mContext, CallBack callBack) {
            this.mContext = mContext;
            mCallBack = callBack;
        }

        public void startCalculation() {
            rx = TrafficStats.getTotalRxBytes();
            time = 0;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.obj = getRxBytes();
                    Log.e(TAG, "schedule: size=" + message.obj);
                    mHandler.sendMessage(message);
                    time++;
                    if (time == 7) stopCalculation();
                }
            }, 1000, 1000);
        }

        public void stopCalculation() {
            if (timer != null) timer.cancel();
            timer = null;
        }

        public interface CallBack {
            void onNetworkSpeed(float b, float kb, float mb, int finish);
        }

        private float getRxBytes() {
            if (rx == 0) rx = TrafficStats.getTotalRxBytes();
            float r = TrafficStats.getTotalRxBytes();
            float r1 = r - rx;
            rx = r;
            if (r1 < 0) r1 = 0;
            return r1;
        }

        private int getAppUid() {
            try {
                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(), 0);
                return info.uid;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return -1;
        }

        int time;
        private static final String TAG = "NetSpeed";

        public void startProcess() {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Request request = new Request.Builder().url(TEST_URL).build();

                    try {
                        Response response = HttpAgent.getOkHttpClient().newCall(request).execute();

                        InputStream inputStream = response.body().byteStream();
                        if (response.isSuccessful()) {
                            startCalculation();
                        } else {
                            stopCalculation();
                        }
                        byte bytes[] = new byte[2 * 1024];
                        while (inputStream.read(bytes) != -1 && timer != null) ;

                    } catch (IOException e) {
                        e.printStackTrace();
                        Message message = new Message();
                        message.what = 1;
                        message.obj = 0f;
                        mHandler.sendMessage(message);
                        stopCalculation();
                    }
                }
            }).start();

        }

        private float bytesForms(String result) {
            System.out.println(result);
            float b = -1;
            float ms = -1;
            Pattern compile = Pattern.compile("\\d+(?=\\sbytes)");
            Matcher matcher = compile.matcher(result);
            while (matcher.find()) {
                b = Float.valueOf(matcher.group());
                System.out.println("b=" + b);
            }
            compile = Pattern.compile("[\\d.]+(?=\\sms)");
            matcher = compile.matcher(result);
            while (matcher.find()) {
                ms = Float.valueOf(matcher.group());
                System.out.println("ms=" + ms);
            }
            compile = Pattern.compile("packets transmitted");
            matcher = compile.matcher(result);
            while (matcher.find()) {
                return -1f;
            }

            compile = Pattern.compile("unknown host");
            matcher = compile.matcher(result);
            while (matcher.find()) {
                return -1f;
            }

            if (b != -1 && ms != -1) {
                return b / ms * 1000;
            } else {
                return -2f;
            }
        }
    }

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            return ni.getState() == NetworkInfo.State.CONNECTED;
        }
        return false;
    }
}
